﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using GeoCoding;
using GeoCoding.Google;
using System.Configuration;
using System.Runtime.Serialization;
using System.Xml.Serialization;

namespace GeocodeServices
{
    /// <summary>
    /// Summary description for GeocodeServices
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class GeocodeServices : System.Web.Services.WebService
    {
        [WebMethod]
        public SerializedAddress GeocodeService(string location)
        {
            GoogleGeoCoder geoCoder = new GoogleGeoCoder(ConfigurationManager.AppSettings["GeocodingApi.Key"]);

            Address geocodeResult = geoCoder.GeoCode(location).FirstOrDefault();

            SerializedAddress address = new SerializedAddress();
            address.Accuracy = geocodeResult.Accuracy.ToString();
            address.City = geocodeResult.City;

            address.Confidence = geocodeResult.Confidence.ToString();
            address.Country = geocodeResult.Country;
            address.PostalCode = geocodeResult.PostalCode;
            address.State = geocodeResult.State;
            address.Street = geocodeResult.Street;
            address.Coordinates = new SerializedCorrdinates(geocodeResult.Coordinates.Latitude, geocodeResult.Coordinates.Longitude);

            return address;
        }
    }

    [Serializable]
    public class SerializedAddress
    {
        public string Accuracy { get; set; }
        public string City { get; set; }
        public string Confidence { get; set; }
        public SerializedCorrdinates Coordinates { get; set; }
        public string Country { get; set; }
        public string PostalCode { get; set; }
        public string State { get; set; }
        public string Street { get; set; }
    }

    [Serializable]
    public class SerializedCorrdinates
    {
        public double Latitude;
        public double Longitude;

        public SerializedCorrdinates()
        {
            Latitude = 0;
            Longitude = 0;
        }

        public SerializedCorrdinates(double lat, double lon)
        {
            this.Latitude = lat;
            this.Longitude = lon;
        }
    }
}
